<template>
	<van-nav-bar title="登录界面" left-text="返回" left-arrow @click-left="onClickLeft" />
	<van-form @submit="onSubmit">
		<van-cell-group inset>
			<van-field
				v-model="user.username"
				name="username"
				label="用户名"
				placeholder="用户名"
				:rules="[{ required: true, message: '请填写用户名' }]"
			/>
			<van-field
				v-model="user.password"
				type="password"
				name="password"
				label="密码"
				placeholder="密码"
				:rules="[{ required: true, message: '请填写密码' }]"
			/>
		</van-cell-group>
		<div style="margin: 16px">
			<van-button round block type="primary" native-type="submit"> 提交 </van-button>
		</div>
	</van-form>
</template>

<script setup>
import {ref} from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant';
import axios from 'axios'

const router = useRouter()

const user = ref({username:'',password:''})

const onClickLeft = () => {
	router.back()
}

/**
 * 提交
 */
const onSubmit = ()=>{
    
    axios({
        url:'http://localhost:3000/login',
        method:'post',
        data:{
            username:user.value.username,
            password:user.value.password
        }
    }).then(res=>{
        if(res.data.code == 1){
            //保存用户信息在本地存储
            const userStr =JSON.stringify(res.data.user) // json对象转json字符串
            localStorage.setItem('userinfo',userStr)

            showToast('登录成功')

            router.replace({path:'/my'})
        }else{
            showToast('用户名或密码出错！')
        }
    })
}

</script>

<style lang="scss" scoped></style>
